﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Configuration;

namespace BaseData.Common
{
    /// <summary>
    /// 日志类
    /// </summary>
    public class LogerHelper
    {
        /// <summary>
        /// 写错误日志
        /// </summary>
        /// <param name="LastError">最后一个错误信息</param>
        public static void WriteError(Exception LastError)
        {
            try
            {
                if ((LastError is System.Threading.ThreadAbortException))
                {
                    return;
                }
                string path = ConfigurationManager.AppSettings["FilePath"];
                string RawUrl = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
                string filepath = path + "/error/" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";

                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }

                //文件不存在即创建
                if (!System.IO.File.Exists(filepath))
                {
                    FileStream fs = System.IO.File.Create(filepath);
                    fs.Close();
                }

                string temp;
                System.IO.StreamWriter sw;

                using (sw = System.IO.File.AppendText(filepath))
                {
                    temp = DateTime.Now.ToString() + "------------------------------------------------------------------------------------" + System.Environment.NewLine;
                    temp += "错误消息:" + LastError.Message + System.Environment.NewLine;
                    temp += "导致错误的应用程序或对象的名称:" + LastError.Source + System.Environment.NewLine;
                    temp += "堆栈内容:" + LastError.StackTrace + System.Environment.NewLine;
                    temp += "引发异常的方法:" + LastError.TargetSite + System.Environment.NewLine;
                    Uri uri = System.Web.HttpContext.Current.Request.UrlReferrer;
                    temp += "页面入口:" + (uri == null ? "null" : uri.AbsoluteUri) + System.Environment.NewLine;
                    temp += "错误页面：" + RawUrl + System.Environment.NewLine + System.Environment.NewLine;
                    sw.WriteLine(temp);
                    sw.Close();
                }
            }
            catch
            {
            }
        }
    }
}
